import React, { useEffect, useRef } from 'react';
import videojs from 'video.js';
import 'video.js/dist/video-js.css';

interface VideoPlayerProps {
  src: string; // 视频地址（支持 m3u8、mp4 等）
  poster?: string;
  controls?: boolean;
  autoPlay?: boolean;
  width?: number | string;
  height?: number | string;
  showControls?: boolean; // 是否显示所有控制栏
}

const VideoPlayer: React.FC<VideoPlayerProps> = ({
  src,
  poster,
  autoPlay = false,
  width = '100%',
  height = '100%', // 默认高度为窗口高度
  showControls = true, // 默认显示控制栏
}) => {
  const videoRef = useRef<HTMLVideoElement>(null);
  const playerRef = useRef<any>(null);

  useEffect(() => {
    // 确保 video 元素存在
    if (!videoRef.current) return;

    // 创建 video.js 播放器实例
    const player = videojs(videoRef.current, {
      controls: showControls, // 控制是否显示所有控制栏
      autoplay: autoPlay,
      preload: 'auto',
      poster,
      playbackRates: [0.5, 1, 1.25, 1.5, 2],
      fluid: true,
      muted: !showControls && autoPlay, // 无控制栏时自动播放需要静音
    });

    // 设置视频源
    player.src({ src }); // 不再限制 type

    // 确保自动播放
    if (autoPlay) {
      const playPromise = player.play();
      if (playPromise !== undefined) {
        playPromise.catch(() => {
          // 如果自动播放失败，尝试静音播放
          player.muted(true);
          player.play();
        });
      }
    }

    // 保存播放器实例
    playerRef.current = player;

    // 组件卸载时清理播放器
    return () => {
      if (playerRef.current) {
        playerRef.current.dispose();
        playerRef.current = null;
      }
    };
  }, []); // 只在组件挂载时初始化播放器

  // 当 src 或其他属性变化时更新播放器
  useEffect(() => {
    if (playerRef.current) {
      playerRef.current.src({
        src,
        type: src.endsWith('.m3u8') ? 'application/x-mpegURL' : undefined,
      });
      playerRef.current.poster(poster);
      playerRef.current.controls(showControls); // 动态更新控制栏显示状态
      playerRef.current.autoplay(autoPlay);
      
      // 更新自动播放状态
      if (autoPlay) {
        playerRef.current.muted(!showControls); // 无控制栏时静音
        const playPromise = playerRef.current.play();
        if (playPromise !== undefined) {
          playPromise.catch(() => {
            playerRef.current.muted(true);
            playerRef.current.play();
          });
        }
      }
    }
  }, [src, poster, showControls, autoPlay]);

  // 外层 div 负责宽高，video 标签不再设置 style
  return (
    <div data-vjs-player>
      <video
        ref={videoRef}
        className="video-js vjs-big-play-centered"
      />
    </div>
  );
};

export default VideoPlayer;
